using System.Collections.Generic;
using Castle.ActiveRecord;
using CosyTrade.Core;
using CosyTrade.Organization;
using NHibernate.Expression;

namespace CosyTrade.Financial
{
    [Addin("FinancialSystem")]
    public class FinancialSystem : AddinBase, IFinancialSystem
    {
        public ExchangeRate GetDefaultExchangeRate(Company company)
        {
            ICriterion searchCriterion =
                Expression.And(Expression.Eq("Company", company), Expression.Eq("CurrentRate", true));
            IList<ExchangeRate> exchanges =
                ActiveRecordMediator<ExchangeRate>.FindAll(new Order[] {Order.Desc("ExchangeIndex")}, searchCriterion);
            if (exchanges.Count > 0) return exchanges[0];
            else return null;
        }

        public void SetDefaultExchangeRate(ExchangeRate exchangeRate)
        {
            ICriterion searchCriterion =
                Expression.And(Expression.Eq("Company", exchangeRate.Company), Expression.Eq("CurrentRate", true));
            IList<ExchangeRate> exchanges = ActiveRecordMediator<ExchangeRate>.FindAll(searchCriterion);
            using (new TransactionScope(OnDispose.Commit))
            {
                foreach (ExchangeRate exchange in exchanges)
                {
                    exchange.IsModifyObject = !exchange.IsNewObject;
                    exchange.CurrentRate = false;
                    ActiveRecordMediator<ExchangeRate>.Update(exchange);
                }
                exchangeRate.IsModifyObject = !exchangeRate.IsNewObject;
                exchangeRate.CurrentRate = true;
                ActiveRecordMediator<ExchangeRate>.Update(exchangeRate);
            }
        }



        public void CreateExchangeRate(ExchangeRate exchangeRate)
        {
            exchangeRate.IsNewObject = true;
            ActiveRecordMediator<ExchangeRate>.Create(exchangeRate);
            if (exchangeRate.CurrentRate) SetDefaultExchangeRate(exchangeRate);
        }

        public IList<ExchangeRate> GetExchangeRateList(Company company)
        {
            ICriterion searchCriterion =
                Expression.And(Expression.Eq("Company", company), Expression.Eq("IsDeleteObject", false));
            return ActiveRecordMediator<ExchangeRate>.FindAll(searchCriterion);
        }

        public ExchangeRate SearchExchangeRate(Company company, int exchangeTime)
        {
            ICriterion searchCriterion =
                Expression.And(Expression.Eq("Company", company), Expression.Eq("IsDeleteObject", false));
            searchCriterion = Expression.And(Expression.Eq("ExchangeIndex", exchangeTime), searchCriterion);
            IList<ExchangeRate> reVal = ActiveRecordMediator<ExchangeRate>.FindAll(new Order[] { Order.Desc("ExchangeIndex") }, searchCriterion);
            if (reVal != null && reVal.Count > 0) return reVal[0];
            else return null;
        }
    }
}